package com.example.geek.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.geek.R;
import com.example.geek.entity.LoginResponse;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText etAccount;
    private EditText etPwd;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        etAccount = findViewById(R.id.et_account);
        etPwd = findViewById(R.id.et_pwd);
        btnLogin = findViewById(R.id.btn_login);
        // 按钮监听器
        TextChange textChange = new TextChange();
        etAccount.addTextChangedListener(textChange);
        etPwd.addTextChangedListener(textChange);
        btnLogin.setEnabled(false);
        btnLogin.setBackgroundResource(R.drawable.shape_forbid_btn);
    }

    private void login(HashMap<String, Object> params) {
        // 登录接口
        OkHttpClient client = new OkHttpClient.Builder()
                .build();
        JSONObject jsonObject = new JSONObject(params);
        String jsonStr = jsonObject.toString();
        RequestBody requestBody = RequestBody.create(jsonStr, MediaType.parse("application/json;charset=utf-8"));
        Request request = new Request.Builder()
                .url("http://47.112.180.188:8080/renren-fast/app/login")
                .addHeader("contentType", "application/json;charset=utf-8")
                .post(requestBody)
                .build();
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("onFailure", e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String result = response.body().string();
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson(result,LoginResponse.class);
                if (loginResponse.getCode() == 0) {
                    String token = loginResponse.getToken();
                    SharedPreferences sp = getSharedPreferences("sp_ttit",MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("token",token);
                    editor.commit();
                    Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }else {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(),"登录失败",Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });
    }

    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(etAccount.getText()) || TextUtils.isEmpty(etPwd.getText())) {
                btnLogin.setEnabled(false);
                btnLogin.setBackgroundResource(R.drawable.shape_forbid_btn);
            } else {
                btnLogin.setEnabled(true);
                btnLogin.setBackgroundResource(R.drawable.shape_login_btn);
                String account = etAccount.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("mobile", account);
                params.put("password", pwd);
                btnLogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        login(params);
                    }
                });
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}